<template>
  <div class="add-editing-dialog">
    <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="标准名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入标准名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="创建人" prop="creator">
              <el-input v-model="formData.creator" placeholder="请输入创建人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="加工标准文档" prop="processCriterionFile">
              <el-upload
                ref="upload"
                class="upload-demo"
                :http-request="saveFileUpload"
                :multiple="true"
                :show-file-list="true"
                :accept="formatFile"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="加工标准信息" prop="processCriterionInfo">
              <div style="border: 1px solid #ccc">
                <Editor
                  style="height: 300px; overflow-y: hidden"
                  v-model="formData.processCriterionInfo"
                  :defaultConfig="editorConfig2"
                  :mode="mode2"
                  @onCreated="handleCreated2"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="saveForm">保 存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { FileFormat, FileSize, PictureFormat } from '@/utils/config'
import * as ProcessCriterionApi from '@/api/processCriterion'
import { onBeforeUnmount, shallowRef } from 'vue'
import { CommonStatusEnum } from '@/utils/constants'
import * as resourceApi from '@/api/resource'
import { FormRules } from 'element-plus'

//加工标准Form
defineOptions({ name: 'ProcessCriterionForm' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 编辑器实例，必须用 shallowRef
const editorRef2 = shallowRef()
const mode2 = 'default' // 或 'simple'
const editorConfig2 = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor2 = editorRef2.value
  if (editor2 == null) return
  editor2.destroy()
})
const handleCreated2 = (editor) => {
  editorRef2.value = editor // 记录 editor 实例，重要！
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: '',
  processCriterionInfo: '',
  processCriterionFile: '',
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProcessCriterionApi.getProcessCriterion(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const getList: any = inject('getList')

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const saveForm = () => {
  formRef.value.validate(async (valid) => {
    console.log(valid)
    if (valid) {
      ProcessCriterionApi.save(formData.value).then((res) => {
        dialogVisible.value = false
        resetForm()
        getList()
      })
    }
  })
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    processCriterionInfo: '',
    processCriterionFile: '',
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}

const saveFileUpload = async (content) => {
  let form = new FormData()
  form.append('file', content.file)
  const data = await resourceApi.uploadFile(form)
  formData.value.processCriterionFile = data.data.previewUrl
}
const formatFile = ref(FileFormat)
//上传前验证文件大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let size = Number(FileSize)
  if (rawFile.size / 1024 / 1024 > Number(FileSize)) {
    ElMessage.error('file size can not exceed ' + size + 'MB!')
    return false
  }
  return true
}
</script>
<style lang="scss" scoped>
.add-editing-dialog {
  width: 100px;
}
</style>
